package com.chdwmp.product.system;

import com.chdwmp.product.bean.CommonResponse;
import com.chdwmp.product.constant.Status;
import com.chdwmp.product.exception.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.SocketTimeoutException;
import java.sql.SQLException;

/**
 * @author jinzhiyuan
 * @create 2020-08-15 19:14
 **/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler({SQLException.class, DataAccessException.class})
    public CommonResponse databaseError(HttpServletRequest request, Exception exception) {
        logger.error("Request: " + request.getRequestURL() + " raised " + exception, exception);
        return new CommonResponse(HttpStatus.BAD_REQUEST.value(), exception.getMessage());
    }

    @ExceptionHandler({CommonException.class})
    public CommonResponse commonException(HttpServletRequest request, CommonException exception) {
        logger.error("Request: " + request.getRequestURL() + " raised " + exception, exception);
        Integer code = null == exception.getCode() ? HttpStatus.BAD_REQUEST.value() : exception.getCode();
        if (Status.SYSTEM_ERROR.getCode().equals(exception.getCode()) || Status.PREPAY_CREATE_ERROR.getCode().equals(exception.getCode())) {
        }
        return new CommonResponse(code, exception.getMessage());
    }

    @ExceptionHandler({Exception.class})
    public CommonResponse exception(HttpServletRequest request, Exception exception) {
        logger.error("Request: " + request.getRequestURL() + " raised " + exception, exception);
        return new CommonResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统异常");
    }

    @ExceptionHandler({SocketTimeoutException.class})
    public CommonResponse SocketTimeoutException(HttpServletRequest request, Exception exception) {
        logger.error("Request: " + request.getRequestURL() + " raised " + exception, exception);
        return new CommonResponse(HttpStatus.REQUEST_TIMEOUT.value(), "请稍后重试");
    }
}
